package com.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dao.AreaDAO;
import com.dao.KefuDAO;
import com.pojo.Area;
import com.pojo.Kefu;
import com.util.MD5Util;
import com.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class KefuService extends ServiceImpl<KefuDAO, Kefu> {
    @Autowired
    private KefuDAO kefuDAO;

    @Autowired
    private AreaDAO areaDAO;

    /**
     * 分页查询客服列表
     * @param page 页数
     * @param limit 条数
     * @param kefuName 客服名
     * @param status 状态
     * @return
     */
    public IPage getKefuPage(int page,int limit,String kefuName,int status){
        Page p=new Page(page,limit);
        QueryWrapper<Kefu> qw=new QueryWrapper<>();
        if (StringUtil.isNotNull(kefuName)){
            qw.like("kefuName",kefuName);
        }
        if(status==0){
            qw.eq("status",status);
        }else if(status==1){
            qw.eq("status",status);
        }

        IPage iPage=kefuDAO.selectPage(p,qw);
        List<Kefu> kefuList = iPage.getRecords();
        for (Kefu kefu :kefuList) {
            Area area = areaDAO.selectById(kefu.getAreaId());
            kefu.setArea(area);
        }
        return iPage;
    }

    /**
     * 修改客服名或密码
     * @param id 客服id
     * @param columName 修改的字段
     * @param value 修改的值
     * @return
     */
    public String edit(String id,String columName,String value){
        Kefu kefu=kefuDAO.selectById(id);
        if (kefu==null){
            return "客服不存在";
        }
        if (StringUtil.isNotNull(columName) && columName.equals("kefuName")){
            List<Kefu> list=kefuDAO.selectList(new QueryWrapper<Kefu>().eq("kefuName",value));
            if (list.size()>0){
                return "客服名重复";
            }
            kefu.setKefuName(value);
        }else if(StringUtil.isNotNull(columName) && columName.equals("password")){
            kefu.setPassword(MD5Util.getMD5(value));
        }
        if (kefuDAO.updateById(kefu)>0){
            return null;
        }else{
            return "修改失败";
        }
    }
}
